const { Menu, dialog } = require('electron')
const got = require('got').default
const path = require('path')
const imageType = require('image-type')
const randomstring = require('randomstring')
const fs = require('fs')

const savers = async (srcUrl) => {
  if (srcUrl) {
    const contextMenu = Menu.buildFromTemplate([
        {
          label:"图片另存为...",
          click:async()=>{
            got(srcUrl).then(async(res)=>{
              const chunk=Buffer.from(res.rawBody);
              const imgType=imageType(chunk);
              // 保存路径+文件名称
              const pathUrl=path.resolve(__dirname,'../../public/uploads/'+randomstring.generate(15)+'.'+imgType.ext)
              // 打开窗口
              const {filePath,canceled}=await dialog.showSaveDialog({
                title:"图片另存为",
                defaultPath:pathUrl
              });
              if(!canceled){
                fs.writeFileSync(filePath,chunk)
              }
            }).catch((e)=>{})
          },
          //快捷键
          accelerator:'CommandOrControl+S'
        }
    ])
    contextMenu.popup()
    return contextMenu
  }
}

module.exports = savers